<?php
/*
 *Crypt.class.php yanr
 *����03:01:22 2011 2011-3-8
 */
class Crypt
{
    private $key = NULL;
    private $iv = NULL;
    private $iv_size = NULL;
    static private $instance;

    static public function getInstance()
    {
        if( self::$instance == NULL ){
            self::$instance = new Crypt();
        }
        
        RETURN self::$instance;
    }
    
    protected function __construct()
    {
        IF( !function_exists('mcrypt_get_iv_size') )
        {
            Logger::trace('Your PHP mcrypt extension is not configured properly');
            throw new Exception('Your PHP mcrypt extension is not configured properly');
        }
    	$this->init( 'iamlock0' );
    }
 
    private function init($key = "")
	{
	    $this->key = ( $key != "" ) ? $key : "";
	 
	    $this->algorithm = MCRYPT_DES;
	    $this->mode = MCRYPT_MODE_ECB;
	 
	    $this->iv_size = mcrypt_get_iv_size( $this->algorithm, $this->mode );
	    $this->iv = mcrypt_create_iv( $this->iv_size, MCRYPT_RAND );
    }
 
    public function encrypt( $data )
    {
	    $size = mcrypt_get_block_size( $this->algorithm, $this->mode );
	    $data = $this->pkcs5_pad( $data, $size );
	    RETURN base64_encode( mcrypt_encrypt( $this->algorithm, $this->key, $data, $this->mode, $this->iv ) );
    }
 
    public function decrypt( $data )
    {
    	RETURN $this->pkcs5_unpad( rtrim( mcrypt_decrypt( $this->algorithm, $this->key, base64_decode( $data ), $this->mode, $this->iv ) ) );
    }
 
    private function pkcs5_pad( $text, $blocksize )
    {
    	$pad = $blocksize - ( strlen( $text ) % $blocksize );
    	RETURN $text . str_repeat( chr( $pad ), $pad );
    }
 
    private function pkcs5_unpad( $text )
    {
	    $pad = ord( $text{ strlen( $text ) - 1 } );
	    IF ( $pad > strlen( $text ) ) RETURN FALSE;
	    IF ( strspn( $text, chr( $pad ), strlen( $text ) - $pad ) != $pad ) RETURN FALSE;
	    RETURN substr( $text, 0, -1 * $pad );
    }
}
?>